﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WDTAsg2.DbBizObject;
using System.Threading;

// This code is a modified version of the code supplied from Shekar's lecture

namespace WDTAsg2.Admin
{
    public partial class ManageUserInfo : System.Web.UI.Page
    {
        private UserInfo _UserService;

        #region Properties

        private string EditUserID
        {
            get
            {
                return (string)ViewState["EditUserID"];
            }

            set
            {
                ViewState["EditUserID"] = value;
            }
        }

        #endregion


        protected void Page_Load(object sender, EventArgs e)
        {
            _UserService = new WDTAsg2.DbBizObject.UserInfo();

            //Load data if not postback
            if (!IsPostBack)
            {
                GridDataBind();
            }
        }


        private void GridDataBind()
        {
            gvUsers.DataSource = WDTAsg2.DbBizObject.UserInfo.GetAllUsers();
            gvUsers.DataBind();
        }


        private void ClearEditUserForm()
        {
            //Empty out text boxes
            var textBoxes = new List<Control>();
            FindControlsOfType(this.phrEditUser, typeof(TextBox), textBoxes);

            foreach (TextBox textBox in textBoxes)
                textBox.Text = "";

            //Clear validators
            var validators = new List<Control>();
            FindControlsOfType(this.phrEditUser, typeof(BaseValidator), validators);

            foreach (BaseValidator validator in validators)
                validator.IsValid = true;
        }


        static public void FindControlsOfType(Control root, Type controlType, List<Control> list)
        {
            if (root.GetType() == controlType || root.GetType().IsSubclassOf(controlType))
            {
                list.Add(root);
            }

            //Skip input controls
            if (!root.HasControls())
                return;

            foreach (Control control in root.Controls)
            {
                FindControlsOfType(control, controlType, list);
            }
        }


        protected void gvUser_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem == null)
                return;

            LinkButton btnEdit = (LinkButton)e.Row.FindControl("btnEdit");
            btnEdit.OnClientClick = "openDialogAndBlock('Edit User', '" + btnEdit.ClientID + "')";
        }


        protected void gvUsers_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string userEmail = e.CommandArgument.ToString();

            switch (e.CommandName)
            {
                //Can't use just Edit and Delete or need to bypass RowEditing and Deleting
                case "EditUser":
                    User User = UserInfo.GetByID(userEmail);

                    FillEditUserForm(User);

                    this.EditUserID = userEmail;
                    RegisterStartupScript("jsUnblockDialog", "unblockDialog();");

                    break;

            }
        }

        private void FillEditUserForm(User user)
        {
            //Populate fields
            txtFirstName.Text = user.FirstName;
            txtLastName.Text = user.LastName;
            txtAge.Text = user.Age.ToString();
            txtAddress.Text = user.Address;

        }


        private void TriggerClientGridRefresh()
        {
            // Refresh
            string script = "__doPostBack(\"" + btnRefreshGrid.ClientID + "\", \"\");";
            RegisterStartupScript("jsGridRefresh", script);
            GridDataBind();

        }


        private void RegisterStartupScript(string key, string script)
        {
            ScriptManager.RegisterStartupScript(phrJsRunner, phrJsRunner.GetType(), key, script, true);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
                return;

            // Update user info pass new params
            UserInfo.UpdateUserByEmail(this.EditUserID.ToString(),
                txtFirstName.Text, txtLastName.Text,
                Convert.ToInt32(txtAge.Text),
                txtAddress.Text);

            HideEditUser();

            TriggerClientGridRefresh();
        }


        private void HideEditUser()
        {
            // Hide the form
            ClearEditUserForm();
            RegisterStartupScript("jsCloseDialg", "closeDialog();");
        }


        protected void btnCancel_Click(object sender, EventArgs e)
        {
            HideEditUser();
        }


        protected void btnRefreshGrid_Click(object sender, EventArgs e)
        {
            GridDataBind();
        }

    }
}